package data_manipulate;

/*
 data are store in rng, 10 row-organized random number:
 1
 3
 4
 2
 ...
 */

import Utils.FileUtil;
import org.apache.hadoop.conf.Configuration;
import org.apache.hadoop.fs.Path;
import org.apache.hadoop.io.IntWritable;
import org.apache.hadoop.io.LongWritable;
import org.apache.hadoop.io.NullWritable;
import org.apache.hadoop.io.Text;
import org.apache.hadoop.mapreduce.Job;
import org.apache.hadoop.mapreduce.Mapper;
import org.apache.hadoop.mapreduce.Reducer;
import org.apache.hadoop.mapreduce.lib.input.FileInputFormat;
import org.apache.hadoop.mapreduce.lib.output.FileOutputFormat;

import java.io.IOException;
import java.util.TreeMap;

public class TopOnRNG {

    public static String inputPath = "hdfs://localhost:9000/top/rng/tmp";
    public static String outputPath = "hdfs://localhost:9000/top/rng/tmp_output";

    public static void main(String[] args)
            throws IOException, InterruptedException, ClassNotFoundException {
        Configuration conf = new Configuration();
        conf.setInt("top",5);
        FileUtil fileUtil = new FileUtil(conf, outputPath);
        fileUtil.doError(inputPath);
        fileUtil.doDelete(outputPath);

        Job job = Job.getInstance(conf, "top-on-RNG");
        job.setJarByClass(TopOnRNG.class);
        // for top problem, we only need on reducer process.
        job.setNumReduceTasks(1);

        job.setMapperClass(doMapper.class);
        job.setMapOutputKeyClass(IntWritable.class);
        job.setMapOutputValueClass(NullWritable.class);

        job.setReducerClass(doReducer.class);
        job.setOutputKeyClass(IntWritable.class);
        job.setOutputValueClass(IntWritable.class);

        for (int i = 0; i < 10; i++) {
            FileInputFormat.addInputPath(job, new Path(inputPath + "/rng" + i + ".txt"));
        }
        FileOutputFormat.setOutputPath(job, new Path(outputPath));

        System.exit(job.waitForCompletion(true) ? 0 : 1);
    }


    public static class doMapper extends Mapper<LongWritable, Text, IntWritable, NullWritable> {

        private int top;
        // TreeMap is sorted in nature, thus by putting items into TreeMap
        // java would automatically sort all existing items.
        private TreeMap<Integer, Integer> numList = new TreeMap<>();

        @Override
        protected void setup(Mapper<LongWritable, Text, IntWritable, NullWritable>.Context context)
                throws IOException, InterruptedException {
            top = context.getConfiguration().getInt("top", 10);
        }

        @Override
        protected void map(LongWritable key, Text value, Mapper<LongWritable, Text, IntWritable, NullWritable>.Context context)
                throws IOException, InterruptedException {
            String splits = value.toString().trim();
            int num = Integer.parseInt(splits);
            numList.put(num, num);
            if (numList.size() > top) {
                numList.remove(numList.firstKey());
            }
        }

        @Override
        protected void cleanup(Mapper<LongWritable, Text, IntWritable, NullWritable>.Context context)
                throws IOException, InterruptedException {
            for (Integer num : numList.values()) {
                System.out.println(num);
                context.write(new IntWritable(num), NullWritable.get());
            }
        }
    }

    public static class doReducer extends Reducer<IntWritable, NullWritable, IntWritable, IntWritable> {

        private int top;
        private TreeMap<Integer, Integer> numList = new TreeMap<>();

        @Override
        protected void setup(Reducer<IntWritable, NullWritable, IntWritable, IntWritable>.Context context)
                throws IOException, InterruptedException {
            top = context.getConfiguration().getInt("top", 10);
        }

        @Override
        protected void reduce(IntWritable key, Iterable<NullWritable> values, Reducer<IntWritable, NullWritable, IntWritable, IntWritable>.Context context)
                throws IOException, InterruptedException {
            int num = key.get();
            numList.put(num, num);
            if (numList.size() > top) {
                numList.remove(numList.firstKey());
            }
        }

        @Override
        protected void cleanup(Reducer<IntWritable, NullWritable, IntWritable, IntWritable>.Context context)
                throws IOException, InterruptedException {
            int cnt = top;
            for (int num : numList.values()) {
                IntWritable numWritable = new IntWritable(num);
                IntWritable id = new IntWritable(cnt);
                context.write(id, numWritable);
                cnt--;
            }
        }
    }
}
